<?php
/**
 * 错误码
 *
 * @date    2018-10-31 17:54:51
 * @version $Id$
 */

namespace App\Commons\Libs\ErrorCode;

use Illuminate\Support\Str;

class ErrorCode
{
    private static $error_code_map;
    private static $name;
    private static $scoped = false;  // 是否闭包中

    public static $current = ['code' => 0, 'msg' => ''];

    public function __construct($name)
    {
        static::$name = $name;
    }

    public function readConfig($locale = null)
    {
        $locale || $locale = app()->getLocale();
        if (static::$error_code_map) {
            return static::$error_code_map[$locale];
        }

        $config = require_once(__DIR__ . '/config.php');
        foreach ($config as $key => $value) {
            $key = str_replace('0x', '', $key);
            $config[$key] = $value;
        }
        static::$error_code_map = $config;

        return static::$error_code_map[$locale] ?? [];
    }

    public function on($err, $code = 500, bool $override = true)
    {
        if ($override) {
            static::$scoped = true;
        }
        if ($code === 500 && is_numeric($err)) {
            // on('msg')
            $code = $err;
            $err = '';
        } elseif (is_bool($code)) {
            // on ('msg', false)
            $override = $code;
            $code = $err;
            $err = '';
        }
        if (is_numeric($code) && $code > 1000) {
            $code = dechex($code);
        }

        $code_str = Str::after($code, '0x');
        $code_str = strtolower($code_str);
        $code_map = $this->readConfig();

        // $hex = str_pad('3e8', 6, '0', STR_PAD_LEFT); // 1000的十六进制
        if (array_key_exists($code_str, $code_map)) {
            static::$current['code'] = $code_str;
            static::$current['msg'] = $err ?: $code_map[$code_str];
            if (empty(static::$current['msg'])) {
                $code_map = $this->readConfig('zh_CN');
                static::$current['msg'] = $code_map[$code_str] ?? '';
            }
        } elseif (!static::$scoped) {
            static::$current['code'] = $code;
            static::$current['msg'] = $err;
        }
    }

    public function off()
    {
        static::$scoped = false;
        static::$current = ['code' => 0, 'msg' => ''];
    }

    public function get()
    {
        $_code = static::$current['code'];
        $_msg = static::$current['msg'];
        return [$_code, $_msg];
    }
}
